# -*- coding: utf-8 -*-
"""
@Time    : 2024/6/26 16:54 
@Author  : ZhangShenao 
@File    : ops.py 
@Desc    : 字符串的常用操作
字符串是用来存放字符的有序序列,其中的元素只能是字符
字符串使用单引号或双引号来表示,通常优先使用单引号
字符串是Immutable的,一旦创建之后,其中的字符就不可修改和删除了
"""

# 通过索引获取str中的字符
s1 = 'abcd'
print(f's1[1] = {s1[1]}')  # s1[1] = b

# 使用index()函数,获取子字符串所在的索引
s2 = 'happy'
print(f'index of "ap" is {s2.index("ap")}')  # index of "ap" is 1
# 如果子字符串不存在,则会抛出异常
# print(f'index of "z" is {s2.index("z")}')  # ValueError: substring not found

# 使用find()函数,获取子字符串所在的索引
# 如果子串不存在,则返回-1,并不会抛出异常
print(f'find of "ap" in s2 is: {s2.find('ap')}')  # find of "ap" in s2 is: 1
print(f'find of "apy" in s2 is: {s2.find('apy')}')  # find of "apy" in s2 is: -1

# 使用in关键字,判断子串是否在字符串中
print(f'"ap" is in s2? {'ap' in s2}')  # "ap" is in s2? True
print(f'"apy" is in s2? {'apy' in s2}')  # "apy" is in s2? False

# 使用count()函数,统计子串在字符串中出现的次数
print(f'count of "app" in s2 is: {s2.count('app')}')  # count of "app" in s2 is: 1
print(f'count of "appz" in s2 is: {s2.count('appz')}')  # count of "appz" in s2 is: 0

# 使用len()函数,获取字符串的长度
s3 = '床前明月光'
print(f'length of s3 is: {len(s3)}')  # length of s3 is: 5

# 使用[start_index:end_index]实现str的切片操作,是一个左闭右开区间
s4 = 'abcdefg'
s5 = s4[2:5]
print(f's5 is: {s5}')  # s5 is: cde
print(f's4 is: {s4}')  # 切片操作会生成一个新的str,原str不变

# 使用+拼接两个str,生成一个新的str
s6 = 'hello'
s7 = 'world'
s8 = s6 + s7
print(f's8 is: {s8}')  # s8 is: helloworld
print(f's6 is: {s6}')  # 拼接后会生成一个新的str,原str不变

# 使用*实现str的复制,生成一个新的str
s9 = 'hello'
s10 = s9 * 3
print(f's10 is: {s10}')  # s10 is: hellohellohello
print(f's9 is: {s9}')  # 复制会生成一个新的str,原str不变
